import {FIRST_PAGE_ROUTE,
HOME_PAGE_ROUTE,HOME_PAGE_NAME,HOME_PAGE_TABNAME} from '../util/constants.js'

import { getToken, setToken, removeToken } from '../util/auth.js';

/*
直接更新状态
 */
export default {
	/**
	 * 添加标签页
	 * @param tabObj  标签页对象.例：{label:"测试",name:"/test"}
	 * */
	addTab(state,tabObj){
		
		//添加的时候需要做一个判断，只有当tabs中不存在当前数据,才需要添加
		let result = state.tabs.find(tab => tab.name === tabObj.name);
		if(!result){
			//添加标签页
			state.tabs.push(tabObj);
			
			//添加缓存页
			state.includeAliveList.push(tabObj.tabName);
			
		}
	},
	/**
	 * 设置活动标签页
	 * */
	setActiveTab(state,activePath){
		//设置之前先记录 之前的活动标签页
		state.oldActiveTab = state.activePath;
		
		//设置活动页面
		state.activePath = activePath;
	},
	/**
	 * 删除标签页
	 * */
	removeTab (state,removeTabName) {
		if(removeTabName===FIRST_PAGE_ROUTE){
			return;
		}
		
		
		let tabs = state.tabs;
		let activeName = state.activePath;
		
		//活动标签页 变成 前面或者后面一个
		if (activeName === removeTabName) {
			tabs.forEach((tab, index) => {
				if (tab.name === removeTabName) {
					let nextTab = tabs[index + 1] || tabs[index - 1];
					if (nextTab) {
					  activeName = nextTab.name;
					}
				}
			});
		}
		//设置活动标签页
		state.activePath = activeName;
		//去掉关闭的页面
		state.tabs = tabs.filter(tab => tab.name !== removeTabName);
		
		//拿取匹配到的tab
		let tabMatchs = tabs.filter(tab => tab.name == removeTabName);
		let tabMatch = tabMatchs[0];
		//删除  关闭的缓存页
		state.includeAliveList = state.includeAliveList.filter(aliveName => aliveName !== tabMatch.tabName);
			
		
	},
	
	
	
	/**
	 * 初始化 左侧导航栏
	 * */
	initNavMenus (state,data) {
	 
		state.navMenus = data;
	},
	
	/**
	 * 	设置活动导航栏
	 * */
	setActiveNav (state,data) {
	 
		state.activeNav = data;
	},
	/**
	 * 保存 右键 的标签页 ID
	 * */
	saveCurTabId(state,data){
		state.curRightClickTabId = data
	},
	/**
	 * 关闭所有 标签页
	 * */
	closeAllTabs(state){
		//关闭除了主页 以外的所有标签
		state.tabs = state.tabs.filter(tab => tab.label== HOME_PAGE_NAME);
		

		//删除  关闭的缓存页
		state.includeAliveList = state.includeAliveList.filter(aliveName => aliveName == HOME_PAGE_TABNAME);
	},
	/**
	 * 关闭其他页 
	 * @param data “/index” 是路径
	 * */
	closeOtherTabs(state,data){
		//关闭除了右键的保存页、主页 以外的所有标签
		state.tabs = 
			state.tabs.filter(tab => (tab.label== HOME_PAGE_NAME || 
										tab.name == state.curRightClickTabId));
		
		
		//拿取匹配到的tab
		let tabMatchs = state.tabs.filter(tab => tab.name == state.curRightClickTabId);
		let tabMatch = tabMatchs[0];
		//删除  关闭的缓存页
		state.includeAliveList = 
			state.includeAliveList.filter(aliveName => (
			aliveName == HOME_PAGE_TABNAME||aliveName == tabMatch.tabName));

	},
	/**
	 * 设置token
	 * */
	setToken(state,data){
		// 保存状态
		 state.token = data;
		 // 写入 
		 setToken(data)
	},
	/**
	 * 删除token
	 * */
	removeToken(state,data){
		 state.token = '';
		 removeToken();
	}
	
	
}